package com.seckill.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seckill.common.domain.R;
import com.seckill.common.exceptions.BadRequestException;
import com.seckill.common.utils.BeanUtils;
import com.seckill.common.utils.CollUtils;
import com.seckill.common.utils.UserContext;
import com.seckill.user.domain.dto.AddressDTO;
import com.seckill.user.domain.po.Address;
import com.seckill.user.service.IAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 地址表 前端控制器
 * </p>
 *
 * @author zsc
 * @since 2025-05-14
 */
@RestController
@RequestMapping("/address")
@RequiredArgsConstructor
@Api(tags = "地址相关接口")
public class AddressController {

    private final IAddressService addressService;

    // 添加地址
    @ApiOperation("添加地址")
    @PostMapping
    public void addAddress(@RequestBody AddressDTO addressDTO) {
        // 1.转换
        Address address = BeanUtils.copyBean(addressDTO, Address.class);
        // 2.设置用户id
        address.setUserId(UserContext.getUser());
        // 3.保存
        addressService.save(address);
    }

    @ApiOperation("根据id查询地址")
    @GetMapping("{addressId}")
    public R<AddressDTO> findAddressById(@ApiParam("地址id") @PathVariable("addressId") Long id) {
        // 1.根据id查询
        Address address = addressService.getById(id);
        // 2.判断当前用户
        Long userId = UserContext.getUser();
        if(!address.getUserId().equals(userId)){
            throw new BadRequestException("地址不属于当前登录用户");
        }
        return R.ok(BeanUtils.copyBean(address, AddressDTO.class));
    }
    @ApiOperation("查询当前用户地址列表")
    @GetMapping
    public R<List<AddressDTO>> findMyAddresses() {
        // 1.查询列表
        List<Address> list = addressService.query().eq("user_id", UserContext.getUser()).list();
        // 2.判空
        if (CollUtils.isEmpty(list)) {
            return R.ok(CollUtils.emptyList());
        }
        // 3.转vo
        return R.ok(BeanUtils.copyList(list, AddressDTO.class));
    }
}
